<?php

/**
 * 
 * @project     : innoTweets 1.0
 * @author      : Dino (DBK)
 * 
 * @package     : Tweet Reply
 * @description : Ajax Operations
 * 
 */
if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class Reply extends AUTH_Controller {

  /**
   * Post tweet reply
   * 
   */
  public function post($tweet_id = NULL) {

	// Checking request method
	if ($this->is_post() && $this->is_ajax()) {

	  // Init vars
	  $result = array('status' => 0, 'msg' => '', 'data' => '');
	  $tweet_hash = NULL;

	  // Getting & cleaning input
	  $tweet_reply = $this->sanitize_html($this->input->post('tweet_reply', TRUE));

	  // Cheking input
	  if (!empty($tweet_id) && is_numeric($tweet_id) && !empty($tweet_reply)) {

		// Getting tweet
		$get_tweet_by_id = $this->tweet_model->get_tweet_by_id($tweet_id);

		// Checking tweet
		if ($get_tweet_by_id['status'] == 1 && !empty($get_tweet_by_id['result'])) {

		  // Saving reply
		  $set_tweet_reply_by_id = $this->tweet_model->set_tweet_reply_by_id($tweet_id, $tweet_reply, $this->current_user['user_id']);

		  // Checking save
		  if ($set_tweet_reply_by_id['status'] == 1 && !empty($set_tweet_reply_by_id['result'])) {

			// Getting saved reply
			$get_tweet_reply_by_id = $this->tweet_model->get_tweet_reply_by_id($tweet_id, 1);

			// Set mentioning notificaion
			$mentioned_users = get_mentioned_users($tweet_reply);
			if (!empty($mentioned_users)) {
			  foreach ($mentioned_users as $mentioned_user) {
				if ($mentioned_user['user_id'] != $this->current_user['user_id']) {
				  $toast_text = '@' . $this->current_user['user_name'] . ' mentioned you in a reply #R' . $set_tweet_reply_by_id['result'];
				  @add_toast_notificaion($mentioned_user['user_id'], $toast_text, 'R' . $set_tweet_reply_by_id['result']);
				}
			  }
			}

			// Set follower notification
			$get_followers = $this->tweet_model->get_followers($tweet_id);
			if (!empty($get_followers['result'])) {
			  foreach ($get_followers['result'] as $follower) {
				if (!empty($follower['user_id']) && ($follower['user_id'] != $this->current_user['user_id'])) {
				  $toast_text = '@' . $this->current_user['user_name'] . ' replied to a tweet #R' . $set_tweet_reply_by_id['result'];
				  @add_toast_notificaion($follower['user_id'], $toast_text, 'R' . $set_tweet_reply_by_id['result']);
				}
			  }
			}

			// Preparing notification hash
			if (!empty($get_tweet_reply_by_id['result'])) {
			  $tweet_hash = md5($get_tweet_reply_by_id['result'][0]['tweet_reply_message']);
			  $result['status'] = 1;
			  $result['msg'] = 'Successfully added tweet reply !';
			  $result['data'] = array('hash' => $tweet_hash);
			}
		  } else {
			$result['msg'] = 'Processing failed !';
		  }
		}
	  }

	  // Responding json
	  die(json_encode($result));
	}

	// Redirect if something wrong
	redirect();
  }

  /**
   * Loading new replies
   * 
   */
  public function new_ajax() {

	// Checking request type
	if ($this->is_post() && $this->is_ajax()) {

	  // Init variables
	  $deleted_reply_ids = array();
	  $reply_data = array();
	  $total_replies_count = 0;
	  $response_array = array('status' => 0, 'new_last_reply_id' => '', 'data' => '');

	  // Getting inputs
	  $tweet_id = $this->input->post('tweet_id', TRUE);
	  $last_reply_id = $this->input->post('last_reply_id', TRUE);

	  // Checking inputs
	  if (!empty($tweet_id) && is_numeric($tweet_id) && !empty($last_reply_id) && is_numeric($last_reply_id)) {

		// Getting tweet data
		$get_tweet_by_id = $this->tweet_model->get_tweet_by_id($tweet_id);

		// Checking tweet data
		if ($get_tweet_by_id['status'] == 1 && !empty($get_tweet_by_id['result'])) {

		  // Getting new tweet replies
		  $get_tweet_new_replies = $this->tweet_model->get_tweet_new_replies($tweet_id, $last_reply_id);

		  // Checking new replies
		  if ($get_tweet_new_replies['status'] == 1 && !empty($get_tweet_new_replies['result'])) {

			// Preparing new reply data
			$tweet_data = $get_tweet_by_id['result'];
			$tweet_reply_data = $get_tweet_new_replies['result'];
			$view_data = array();
			$view_data['tweet_data'] = $tweet_data;

			// Generating html of new replies
			foreach ($tweet_reply_data as $tweet_reply) {
			  $html_data = array();
			  $view_data['tweet_reply'] = $tweet_reply;
			  $html_data['reply_html'] = trim($this->load->view('reply_new_ajax', $view_data, TRUE));
			  $html_data['reply_id'] = $tweet_reply['tweet_reply_id'];
			  $reply_data[] = $html_data;
			}
		  }
		}

		// Getting deleted reply ids (soft delete)
		$get_deleted_replies = $this->tweet_model->get_deleted_replies($tweet_id, NULL);
		if ($get_deleted_replies['status'] == 1 && !empty($get_deleted_replies['result'])) {
		  foreach ($get_deleted_replies['result'] as $deleted_reply) {
			$deleted_reply_ids[] = $deleted_reply['tweet_reply_id'];
		  }
		}

		// Getting last loaded reply id
		if (!empty($tweet_reply_data)) {
		  $last_data = end($tweet_reply_data);
		  $new_last_reply_id = $last_data['tweet_reply_id'];
		} else {
		  $new_last_reply_id = 0;
		}

		// Getting total replies of the tweet
		$get_tweet_extras = $this->tweet_model->get_tweet_extras($tweet_id, $this->current_user['user_id']);
		$total_replies_count = (int) $get_tweet_extras['result']['tweet_total_replies_count'];
		$my_replies_count = (int) $get_tweet_extras['result']['tweet_my_replies_count'];

		// Getting tweet followers
		$get_followers = $this->tweet_model->get_followers($tweet_id);
		$tweet_followers_count = (int) $get_followers['count'];

		// Getting tweet repliers
		$repliers_data = NULL;
		$get_tweet_users = $this->tweet_model->get_tweet_users($tweet_id);
		$view_data = array();
		$view_data['tweet_users_data'] = $get_tweet_users['result'];
		$repliers_data = trim($this->load->view('ajax/tweet_repliers', $view_data, TRUE));

		// Getting & Setting tweet viewers
		$viewers_data = NULL;
		$tweet_viewers = tweet_viewers($tweet_id);
		if (!empty($tweet_viewers) && is_array($tweet_viewers)) {
		  $view_data = array();
		  $view_data['tweet_viewers'] = $tweet_viewers;
		  $viewers_data = trim($this->load->view('ajax/tweet_viewers', $view_data, TRUE));
		}

		// Respond Json
		$response_array = array();
		$response_array['status'] = 1;
		$response_array['data'] = $reply_data;
		$response_array['new_last_reply_id'] = $new_last_reply_id;
		$response_array['deleted_reply_ids'] = $deleted_reply_ids;
		$response_array['total_replies_count'] = $total_replies_count;
		$response_array['my_replies_count'] = $my_replies_count;
		$response_array['tweet_followers_count'] = $tweet_followers_count;
		$response_array['repliers_data'] = $repliers_data;
		$response_array['repliers_count'] = (int) count($get_tweet_users['result']);
		$response_array['viewers_data'] = $viewers_data;
		$response_array['viewers_count'] = (int) count($tweet_viewers);

		die(json_encode($response_array));
	  }
	}

	// Redirect if something wrong
	redirect();
  }

  /**
   * Function to generate html for viewers thumb image
   * 
   */
  private function viewer_thumb($user_id = NULL, $user_name = NULL, $user_image = NULL) {
	$profile_url = base_url('profile/' . $user_name);
	$image_url = base_url('assets/photos/' . $user_image);
	$thumb_html = '<a id = "tweet_viewer_' . $user_id . '" title = "@' . $user_name . '" href = "' . $profile_url . '">';
	$thumb_html .= '<img class = "thumbnail pull-left" style = "max-width: 32px; max-height: 32px; margin: 4px;" src = "' . $image_url . '"/>';
	$thumb_html .= '</a>';
	return $thumb_html;
  }

  /**
   * Delete a reply
   * 
   * Can do by replied user or admin
   * 
   */
  public function delete($reply_id = NULL) {

	// Checking request type
	if ($this->is_post() && $this->is_ajax()) {

	  // Init vars
	  $result = array('status' => 0, 'msg' => '', 'data' => '');

	  // Checking reply id
	  if (!empty($reply_id) && is_numeric($reply_id)) {

		// Checking request is by admin or user
		if ($this->is_admin) {
		  $this->like_model->del_likes_by_post('reply', $reply_id);
		  $del_tweet_reply_by_id = $this->tweet_model->delete_reply($reply_id);
		} else {
		  $this->like_model->del_likes_by_post('reply', $reply_id);
		  $del_tweet_reply_by_id = $this->tweet_model->del_tweet_reply_by_id($reply_id, $this->current_user['user_id']);
		}

		// Checking delete process
		if ($del_tweet_reply_by_id['status'] == 1 && !empty($del_tweet_reply_by_id['result'])) {
		  $result['status'] = 1;
		  $result['msg'] = 'Successfully deleted tweet reply !';
		} else {
		  $result['msg'] = 'Processing failed !';
		}
	  } else {
		$result['msg'] = 'Invalid reply id !';
	  }

	  // Responding json
	  die(json_encode($result));
	}

	// Redirect if something wrong
	redirect();
  }

  /**
   * Load more replies
   * 
   */
  public function load_old_replies() {

	// Checking request type
	if ($this->is_post() && $this->is_ajax()) {

	  // Preparing response array
	  $response_array = array('status' => 1, 'new_last_loaded_reply_id' => 1, 'data' => NULL, 'has_more' => 0);

	  // Getting inputs
	  $tweet_id = $this->input->post('tweet_id', TRUE);
	  $last_loaded_reply_id = $this->input->post('last_loaded_reply_id', TRUE);
	  $replies_sort_by = $this->input->post('replies_sort_by', TRUE);
	  $load_all = $this->input->post('replies_load_all', TRUE);

	  // Setting limit value
	  $replies_sort_by = ($replies_sort_by == 2) ? 2 : 1;
	  $limit = ($load_all == 1) ? NULL : 10;

	  // Checking inputs
	  if (!empty($tweet_id) && !empty($last_loaded_reply_id) && is_numeric($tweet_id) && is_numeric($last_loaded_reply_id)) {

		// Getting tweet details
		$get_tweet_by_id = $this->tweet_model->get_tweet_by_id($tweet_id);

		if ($get_tweet_by_id['status'] == 1 && !empty($get_tweet_by_id['result'])) {

		  // Get old replies
		  $get_old_replies = $this->tweet_model->get_tweet_old_replies($tweet_id, $last_loaded_reply_id, $replies_sort_by, $limit);

		  // Checking old replies
		  if ($get_old_replies['status'] == 1 && !empty($get_old_replies['result'])) {

			// Preparing reply
			$tweet_data = $get_tweet_by_id['result'];
			$tweet_reply_data = $get_old_replies['result'];
			$view_data = array();
			$view_data['tweet_data'] = $tweet_data;
			foreach ($tweet_reply_data as $tweet_reply) {
			  $html_data = array();
			  $view_data['tweet_reply'] = $tweet_reply;
			  $html_data['reply_html'] = trim($this->load->view('reply_new_ajax', $view_data, TRUE));
			  $html_data['reply_id'] = $tweet_reply['tweet_reply_id'];
			  $reply_data[] = $html_data;
			}

			if ($replies_sort_by == 2) {
			  $new_last_loaded_reply_id = (int) $last_loaded_reply_id + 10;
			} else {
			  $reply_array_end = end($get_old_replies['result']);
			  $new_last_loaded_reply_id = (int) $reply_array_end['tweet_reply_id'];
			}

			// Checking weather any more replies
			$has_more = 0;
			if (!empty($new_last_loaded_reply_id) && $load_all != 1) {
			  $get_old_replies = $this->tweet_model->get_tweet_old_replies($tweet_id, $new_last_loaded_reply_id, $replies_sort_by, $limit);
			  if ($get_old_replies['status'] == 1 && !empty($get_old_replies['result'])) {
				$has_more = 1;
			  }
			}

			// Setting response
			$response_array = array('status' => 1, 'new_last_loaded_reply_id' => $new_last_loaded_reply_id, 'data' => $reply_data, 'has_more' => $has_more);
		  }
		}
	  }

	  // Responding json
	  echo json_encode($response_array);
	  return;
	}

	// Redirect if invalid request
	redirect();
  }

  /**
   * Set & Get user ids of current viewers of tweet
   * 
   * Using PHP APC
   * 
   */
  private function tweet_viewers($tweet_id = NULL) {

	// Checking tweet id
	if (!empty($tweet_id) && is_numeric($tweet_id)) {

	  // Check, need to add current user to viewers
	  if ($this->current_user['user_online_mode'] == 1) {
		$tweet_viewers = (array) $this->cache->get('viewers_tweet_' . $tweet_id);
		if (!empty($tweet_viewers) && is_array($tweet_viewers)) {
		  $tweet_viewers = (array) array_filter(array_unique(array_merge($tweet_viewers, array($this->current_user['user_id']))));
		  $this->cache->delete('viewers_tweet_' . $tweet_id);
		  $this->cache->save('viewers_tweet_' . $tweet_id, $tweet_viewers, 60);
		}
	  }

	  // Getting user ids from cache
	  $user_ids = (array) $this->cache->get('viewers_tweet_' . $tweet_id);

	  // Getting user details using user id
	  $get_users_by_ids = $this->user_model->get_users_by_ids($user_ids);

	  return $get_users_by_ids['result'];
	}

	// Return a null array if something wrong
	return NULL;
  }

}

?>